﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.Threading;
using System.Xml.XPath;
using Shoozla.DataModel.Helper;

namespace Shoozla.DataModel
{

    public class PLAYMESearcher : CoverSearcher
    {

        public String APPKEY { get; set; }
        private int _artistCode;

        public PLAYMESearcher(ICoverStorage cache, CancellationTokenSource token, StatisticsLogger stats) : base(cache, token,stats) { APPKEY = "4f6752545943734901"; }
        public PLAYMESearcher() { APPKEY = "4f6752545943734901"; }

        public override bool Initialize() {
                return true; 
        }

        protected override void SetAddInInformation()
        {
            AddInName = "PLAY.ME";
            AddInDescription = "It uses the playme.com websiste, no account needed";
        }

        public override Image GetIcon()
        {
            return Properties.Resources.logo;
        }

        #region Virtual methods
        
        public override Uri FindByAlbumNameInternal(String artist,String albumName)
        {
            if (String.IsNullOrEmpty(artist) || String.IsNullOrEmpty(albumName))
                return null;
            try
            {
                //String albumUrl = @"http://api.playme.com/album.searchByName?query=" + StringHelper.PrepareStringForWeb(albumName) + @"&country=us&apikey=" + APPKEY;
                //XPathDocument albums = new XPathDocument(albumUrl);
                //XPathNavigator nav = albums.CreateNavigator();
                //XPathNodeIterator it = nav.Select("//album");
                //while(it.MoveNext())
                //{
                   
                //   String webAlbumName = it.Current.SelectSingleNode("//name").Value;

                //   if (webAlbumName.ToLowerInvariant().Contains(albumName.ToLowerInvariant()))
                //   { 
                //        XPathNavigator url = it.Current.SelectSingleNode("//images/img_256");
                //        string albumurl = url.Value;
                //         if(!String.IsNullOrEmpty(albumurl))
                //            return new Uri(albumurl, UriKind.Absolute);
                //   }
                //}

                //return null;

                _artistCode = FindArtistCode(artist);
                String albumUrl = @"http://api.playme.com/artist.getAlbums?artistCode=" + _artistCode + "&" + StringHelper.PrepareStringForWeb(albumName) + @"&step=50&country=us&apikey=" + APPKEY;
                XPathDocument albums = new XPathDocument(albumUrl);
                XPathNavigator nav = albums.CreateNavigator();
                XPathNodeIterator it = nav.Select("//album");
                while (it.MoveNext())
                {

                    String webAlbumName = it.Current.SelectSingleNode("name").Value;

                    if (webAlbumName.ToLowerInvariant().Contains(albumName.ToLowerInvariant()))
                    {
                        XPathNavigator url = it.Current.SelectSingleNode("images/img_256");
                        string albumurl = url.Value;
                        if (!String.IsNullOrEmpty(albumurl))
                            return new Uri(albumurl, UriKind.Absolute);
                    }
                }

                return null;

            }
            catch (Exception albumEx)
            {
                Trace.WriteLine(String.Format("[ERROR] PlayMeSearcher: FindByAlbumName: {0} - {1} ", albumName, albumEx.Message));
                return null;
            }
        }

        public override Uri FindBySongTitleInternal(String artist, String title)
        {
            try
            {
                String albumUrl = @"http://api.playme.com/track.searchByName?artistcode=" + _artistCode+ "&query=" + StringHelper.PrepareStringForWeb(title) + @"&country=us&step=50&apikey=" + APPKEY;
                XPathDocument albums = new XPathDocument(albumUrl);
                XPathNavigator nav = albums.CreateNavigator();
                XPathNodeIterator it = nav.Select("//track");
                while(it.MoveNext())
                {
                   
                   String webAlbumName = it.Current.SelectSingleNode("name").Value;

                   if (webAlbumName.ToLowerInvariant().StartsWith(title.ToLowerInvariant()))
                   { 
                        XPathNavigator url = it.Current.SelectSingleNode("images/img_256");
                        string coverUrl = url.Value;
                        if (!String.IsNullOrEmpty(coverUrl))
                             return new Uri(coverUrl, UriKind.Absolute);
                   }
                }
                return null;
            }
            catch (Exception albumEx)
            {
                Trace.WriteLine(String.Format("[ERROR] PlayMeSearcher: FindBySongTitle: {0} - {1}",title,albumEx.Message));
                return null;
            }
        }

        public override Uri FindArtistInternal(String artist)
        {
            try
            {
                String artistiUrl = @"http://api.playme.com/artist.searchByName?query=" + StringHelper.PrepareStringForWeb(artist) + @"&country=us&apikey=" + APPKEY;
                XPathDocument artistUrl = new XPathDocument(artistiUrl);
                XPathNavigator nav = artistUrl.CreateNavigator();
                XPathNodeIterator it = nav.Select("//artist");
                while (it.MoveNext())
                {

                    String webArtistName = it.Current.SelectSingleNode("name").Value;
                    if (webArtistName.ToLowerInvariant() == artist.ToLowerInvariant())
                    {
                        XPathNavigator url = it.Current.SelectSingleNode("images/big");
                        string coverUrl = url.Value;
                        if (!String.IsNullOrEmpty(coverUrl))
                            return new Uri(coverUrl, UriKind.Absolute);
                    }
                }
                return null;
            }
            catch (Exception albumEx)
            {
                Trace.WriteLine(String.Format("[ERROR] PlayMeSearcher: FindArtist: {0} - {1}", artist, albumEx.Message));
                return null;
            }
        }


        private int FindArtistCode(String artist)
        {
            try
            {
                String artistiUrl = @"http://api.playme.com/artist.searchByName?query=" + StringHelper.PrepareStringForWeb(artist) + @"&country=us&apikey=" + APPKEY;
                XPathDocument artistUrl = new XPathDocument(artistiUrl);
                XPathNavigator nav = artistUrl.CreateNavigator();
                XPathNodeIterator it = nav.Select("//artist");
                while (it.MoveNext())
                {
                    String webArtistName = it.Current.SelectSingleNode("name").Value;
                    if (webArtistName.ToLowerInvariant() == artist.ToLowerInvariant())
                    {
                        XPathNavigator url = it.Current.SelectSingleNode("artistCode");
                        string code = url.Value;
                        return Int32.Parse(code);
                    }
                }
                return -1;
            }
            catch (Exception albumEx)
            {
                Trace.WriteLine(String.Format("[ERROR] PlayMeSearcher: FindArtistCode: {0} - {1}", artist, albumEx.Message));
                return -1;
            }
        }

        #endregion
    }
}
